<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

/**
 * CsvCreator Class
 *
 * @author			Myra Katrina Oliveros
 * @date created	March 12, 2010
 * @date modified	March 12, 2010
 * @version			1.0
 * 
 * Compatible with Codeigniter 1.7.2
 */

class CsvCreator {
	
	var $type = 'table'; 		// from what format
	var $title = '';			// text before column headers and rows
	var $cols = array();		// headers
	
	// if type is table, set
	var $tr = '';				// rows in html string (<tr><td></td></tr>)
	
	var $prefix = ''; 			// filename prefix
	var $dir = '';				// where to save the newly created csv
	var $filename = ''; 		// csv filename. no file extension
	var $file_ext = '.csv';		// file extension
	var $overwrite = FALSE;		// overwrite existing files?
	
	var $delimiter = ','; 		// field delimiter
	var $newline = "\r\n";		// newline break
	
	
	var $headers = '';
	var $rows = '';
	
	var $CI;
	
	function __construct($params = array())
	{
		if (count($params) > 0)
		{
			$this->initialize($params);		
		}
		
		$this->CI =& get_instance();
		$this->CI->load->helper('file');
	}
	
	/**
	 * initialize
	 * 
	 * Sets configurable variables
	 * 
	 * @access public
	 * @params array
	 * @return void
	 */
	function initialize($params = array())
	{
		if (count($params) > 0)
		{
			foreach ($params as $key => $val)
			{
				if (isset($this->$key))
				{
					$this->$key = $val;
				}
			}
		}
	}
	
	/**
	 * create_csv
	 * 
	 * Creates csv
	 * 
	 * @access public
	 * @param void
	 * @return boolean
	 */
	function create_csv()
	{
		// set headers first
		$this->_set_headers();
		
		// set csv rows
		if ($this->type == 'table')
		{
			$this->_set_rows_table();
		}
		
		// if no filename defined, use timestamp
		if (empty($this->filename)) $this->filename = time();
		
		// set file name, overwrite taken into consideration		
		$this->_set_filename();
		
		// check directory, stop on error
		if ( ! $this->validate_dir()) return FALSE;
		
		// set csv full path
		$path = $this->dir . $this->prefix . $this->filename . $this->file_ext;
		
		// write the csv
		$data = ( ! empty($this->title)) ?  $this->title . $this->newline : '';
		
		$data .= $this->headers . $this->rows;
		if ( ! write_file($path, $data))
		{
			show_error('Unable to write CSV.');
			return FALSE;
		}
		
		return TRUE;
	}
	
	/**
	 * get_full_path
	 * 
	 * Gets full path of csv
	 * 
	 * @access public
	 * @param void
	 * @return string
	 */
	function get_full_path()
	{
		return $this->dir . $this->prefix . $this->filename . $this->file_ext;
	}
	
	/**
	 * get_filename
	 * 
	 * Gets csv filename with extension
	 * 
	 * @access public
	 * @param void
	 * @return string
	 */
	function get_filename()
	{
		return $this->prefix . $this->filename . $this->file_ext;
	}
	
	/**
	 * _set_headers
	 * 
	 * Sets csv headers
	 * 
	 * @access private
	 * @param void
	 * @return void
	 */
	function _set_headers()
	{
		$this->headers = '';
		
		foreach ($this->cols as $i => $val)
		{
			$this->headers .= '"'. $val .'"'. $this->delimiter;
		}
		
		$this->headers .= $this->newline;
	}
	
	/**
	 * _set_rows_table
	 * 
	 * Sets csv rows from html string
	 * 
	 * @access private
	 * @param void
	 * @return void
	 */
	function _set_rows_table()
	{
		$this->rows = '';
		
		/*
		 * prep html string
		 * replace &nbsp; with spaces
		 * rows must not have rowspan attribute
		 */
		
		$str = str_replace('&nbsp;', ' ', $this->tr);
				
		// split html string into rows
		$a_rows = explode('</tr>', $str);
		
		// traverse rows
		$rows = '';
		foreach ($a_rows as $i => $row)
		{
			/*
			 * remove <tr ...>
			 * cannot do str_replace. will fail if there are attributes defined
			 */
			
			$row = substr($row, strpos($row, '>') + 1);
			
			$a_row = explode('</td>', $row);
			
			$cols = '';
			// traverse fields
			foreach ($a_row as $j => $col)
			{
				/*
				 * remove <td ...>
				 * same with rows, remove attributes defined 
				 * ignores all attributes in tag
				 */
				
				$col = substr($col, strpos($col, '>') + 1);
				$cols .= '"'. $col .'"'. $this->delimiter;
			}
			
			$rows .= $cols . $this->newline;
		}
		
		$this->rows = $rows;
	}
	
	/**
	 * validate_dir
	 *
	 * Checks dir specified. From File Uploading Class.
	 *
	 *
	 * @access public
	 * @param void
	 * @return boolean
	 */	
	function validate_dir()
	{
		if ($this->dir == '')
		{
			show_error('No directory specified.');
			return FALSE;
		}
		
		if (function_exists('realpath') AND @realpath($this->dir) !== FALSE)
		{
			$this->dir = str_replace("\\", "/", realpath($this->dir));
		}

		if ( ! @is_dir($this->dir))
		{
                        echo $this->dir;
			show_error('Invalid directory specified.');
			return FALSE;
		}

		if ( ! is_really_writable($this->dir))
		{
			show_error('Diretory specified not writable.');
			return FALSE;
		}

		$this->dir = preg_replace("/(.+?)\/*$/", "\\1/",  $this->dir);
				
		return TRUE;
	}
	
	/**
	 * _set_filename
	 *
	 * Sets csv filename. From File Uploading Class (modified)
	 *
	 * @access private
	 * @param void
	 * @return void
	 */	
	function _set_filename()
	{
		if ( ! file_exists($this->dir . $this->filename . $this->file_ext))
		{
			return TRUE; 
		}
		
		// ovewrite existing file
		if ($this->overwrite !== FALSE) return TRUE;
		
		$new_filename = '';
		for ($i = 1; $i < 100; $i++)
		{			
			if ( ! file_exists($this->dir . $this->filename . $i . $this->file_ext))
			{
				$new_filename = $filename . $i;
				break;
			}
		}

		if ($new_filename == '')
		{
			show_error('Invalid CSV file name.');
			return FALSE;
		}
		
		$this->filename = $new_filename;
	}
}

/* End of file CsvCreator.php */
/* Location: ./system/application/libraries/CsvCreator.php */
